package monitTree;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import db_tool.DBConnection;
import org.apache.struts2.ServletActionContext;
import tree_util.Account;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SearchPage extends ActionSupport {
	
	private String searchData;
	
	//树节点分页
	private int pageSize = 18;
	private int pageNumber = 1;

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	private Account account = (Account) ActionContext.getContext().getSession().get("account");
	
	//获取所有的监测点
	public String execute() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter writer = ServletActionContext.getResponse().getWriter();
		//获取session中保存的用户信息
		//account = (Account) ActionContext.getContext().getSession().get("account");
		/*System.out.println("数据："+searchData);*/
		String sql = "";
		StringBuffer buf = new StringBuffer();
		String subbuf;
		String[] monitID = searchData.split(",");
		for (int i=0;i<monitID.length;i++) {
			buf.append("'"+monitID[i]+"'").append(",");
		}
		subbuf = buf.substring(0, buf.length()-1);
		/*System.out.println(subbuf);*/
		DBConnection dbConnection = DBConnection.getInstance();
		Statement statement = null;
		ResultSet rs = null;
		try {
			statement = dbConnection.getStatement();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		sql = "select top "+pageSize+" InverstigationID from MonitoringSite where InverstigationID > ( select isnull(max(InverstigationID),0) from (select top ("+pageSize+" * ("+pageNumber+"-1)) InverstigationID from MonitoringSite where InverstigationID in ("+subbuf+") order by InverstigationID ) tb) and InverstigationID in ("+subbuf+")";
		System.out.println(sql);
		 
		String result="";
		
		try {
			rs = statement.executeQuery(sql);
			while(rs.next()){
				result+=rs.getString(1)+",";
			}
			if(result.length()==0){writer.write("error");}
			else{
			result = result.substring(0, result.length()-1);
			writer.write(result);
			}
			
			System.out.println("monitSite ID result:"+result);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writer.write("error");
		} finally{
			try {
				dbConnection.close(rs,statement);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return null;
	}

	public String getSearchData() {
		return searchData;
	}

	public void setSearchData(String searchData) {
		this.searchData = searchData;
	}
	
}
